package com.saascloud.core;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.saascloud.config.properties.SmsProperties;
import com.saascloud.core.exception.BizException;
import com.saascloud.core.exception.GlobalErrorCode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: one_dream@aliyun.com
 * @date: Created in 2022/8/19 14:24
 * @description
 */
@Slf4j
@Data
public class SmsSend {

    @Autowired
    private SmsProperties smsProperties;
    @Autowired(required = false)
    private StringRedisTemplate stringRedisTemplate;

    public String token() {
        Map<String, Object> dict = new HashMap<>();
        dict.put("client_id", smsProperties.getClientId());
        dict.put("client_secret", smsProperties.getClientSecret());
        dict.put("grant_type", smsProperties.getGrantType());
        dict.put("scope", smsProperties.getScope());
        String cacheKey = String.join(":", smsProperties.getTokenUrl(), smsProperties.getClientId(), smsProperties.getGrantType(), smsProperties.getScope());
        if (stringRedisTemplate != null) {
            String cacheToken = stringRedisTemplate.opsForValue().get(cacheKey);
            if (StringUtils.hasText(cacheToken)) {
                log.debug("从缓存中获取token:{}", cacheToken);
                return cacheToken;
            }
        }
        String token = null;
        HttpResponse response = HttpRequest.post(smsProperties.getTokenUrl())
                .form(dict)
                .timeout(smsProperties.getTimeout())
                .execute();
        if (!response.isOk()) {
            throw new BizException(GlobalErrorCode.INTERNAL_SERVER_ERROR.getCode(), "token授权失败");
        }
        JSONObject ojson = JSONObject.parseObject(response.body());
        log.info("getToken获取IpsaToken成功token:{}", ojson.getString("access_token"));
        token = ojson.getString("access_token");
        if (stringRedisTemplate != null) {
            stringRedisTemplate.opsForValue().set(cacheKey, token, 60, TimeUnit.MINUTES);
        }
        return token;
    }


    public void sendMessage(String mobile, String content) {
        String url = smsProperties.getSmsUrl();
        JSONObject param = new JSONObject();
        param.put("mobile", mobile);
        param.put("label", smsProperties.getLabel());
        param.put("content", content);
        log.info("RelationOtherSystemServiceImpl.sendMessage调用消息平台发送短信接口参数={},请求地址:{}", param, url);
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + token())
                .contentType("application/json")
                .body(param.toJSONString())
                .timeout(smsProperties.getTimeout())
                .execute();
        log.info("消息平台返回:{}", response.body());
        if (!response.isOk()) {
            throw new BizException(GlobalErrorCode.INTERNAL_SERVER_ERROR.getCode(), "消息平台请求失败:" + response.body());
        }
        String body = response.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (!new Integer(0).equals(jsonObject.getInteger("code"))) {
            throw new BizException(GlobalErrorCode.INTERNAL_SERVER_ERROR.getCode(), "短信发生失败:" + response.body());
        }
    }

    public static void main(String[] args) {
        SmsSend smsSend = new SmsSend();
        SmsProperties smsProperties = new SmsProperties();
        smsProperties.setTokenUrl("https://api.isoftstone.com/ids/connect/token");
//        smsProperties.setSmsUrl("https://api.isoftstone.com/iSSC/msgServiceTest/1.0/msgOtherSystem/insertList");
        smsProperties.setSmsUrl("http://api.isoftstone.com/iSSC/msgServiceTest/1.0/sendMessage");
        smsProperties.setClientId("62f9be19-8c58-4e97-8249-9f418cccda7c");
        smsProperties.setClientSecret("17ad1cdd-b5e7-461f-8741-8e62a94cbfb0");
        smsProperties.setGrantType("client_credentials");
        smsProperties.setScope("msgServiceTest");
        smsSend.setSmsProperties(smsProperties);
        smsSend.sendMessage("17762521714", "ldy测试短信");
    }
}
